package org.nokatag.system;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class IbatisUtil {
private static SqlSessionFactory sqlSessionFactory;
public static final ThreadLocal<SqlSession> session = new ThreadLocal<SqlSession>();

public static SqlSession currentSession(){
	SqlSession s = (SqlSession) session.get();
	//-----------------------------------------------------------
	try{
		if(s.getConnection().isClosed()){
			try{s.close();}catch(Exception se){BugInfoWrint.Print(se);}
			session.remove();
			s=null;
		}
	}catch(Exception se){
		s=null;
	}
	//-----------------------------------------------------------
	if (s == null) {
		currentNewSession();
		s = (SqlSession) session.get();
	}
	return s;
}

public static SqlSession currentNewSession(){
	SqlSession s = sqlSessionFactory.openSession();
	s.clearCache();
	session.set(s);
	return s;
}

public static void closeSession(){
	SqlSession s = (SqlSession) session.get();
	session.set(null);
	if (s != null) {
		s.close();
	}
}

public static void closeSession(SqlSession session) {
	try {
		if (session != null) {
			session.close();
		}
	} catch (Exception e) {
		BugInfoWrint.Print(e);
	}
}


static {
	try {
		String resource = "ibatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	} catch (Exception  ex) {
		 ex.printStackTrace();
	}
}
}
